package com.lyc.api.controller;

import com.google.gson.reflect.TypeToken;
import com.lyc.api.VO.ResultVO;
import com.lyc.api.exception.BookException;
import com.lyc.api.service.BookCollectService;
import com.lyc.api.utils.ResultVOUtil;
import com.lyc.common.enums.ResultEnum;
import com.lyc.common.model.BookCollect;
import com.lyc.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 书架
 * Created by 廖师兄
 * 2017-05-29 17:22
 */
@RestController
@RequestMapping("/bookCollect")
public class BookCollectController {

    @Autowired
    private BookCollectService collectService;

    @GetMapping("/list")
    public ResultVO list(@RequestParam String token) {
        List<BookCollect> bookCollectList = collectService.list(token);

        HashMap<String, List<BookCollect>> mapResponse = new HashMap<>();
        mapResponse.put("bookCollects", bookCollectList);
        return ResultVOUtil.success(mapResponse);
    }

    @PostMapping("/add")
    public ResultVO add(@RequestParam String token,
                        @RequestParam String bookId) {
        BookCollect bookCollect = collectService.add(token, bookId);
        if (bookCollect != null) {
            return ResultVOUtil.success(bookCollect);
        }else {
            return ResultVOUtil.error(ResultEnum.UNKNOW_ERROR);
        }

    }

    @PostMapping("/delete")
    public ResultVO delete(@RequestParam("collectIds") String collectIds) {
        List<String> collectIdList = new ArrayList<>();
        try {
            collectIdList = JsonUtil.fromJson(collectIds, new TypeToken<List<String>>() {
            }.getType());
        }catch (Exception e) {
            throw new BookException(ResultEnum.PARAM_ERROR);
        }
        Integer result = collectService.delete(collectIdList);
        if (result > 0) {
            return ResultVOUtil.success();
        }else {
            return ResultVOUtil.error(ResultEnum.DELETE_ERROR);
        }
    }

}
